package com.thinkgem.jeesite.modules.weixin.pageauthorization;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 获取用户openid
 *
 * @author liyuefan
 * @version 1.0
 * @since 2015-12-4
 */
public class Auth2UserInfo {
	private static final Logger logger = LoggerFactory.getLogger(Auth2UserInfo.class);

	private static final String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

	private static AccountConfig accountConfig;

	private static String appId = "";
	private static String appSecret = "";

	static {
		accountConfig = new AccountConfig();
		accountConfig.getConfig();
		appId = accountConfig.getAppId();
		appSecret = accountConfig.getAppSecret();
	}

	/**
	 * 根据code获取openId
	 * @param code
	 * @return
	 */
	public static String getOpenId(String code) {

		String reqUrl = String.format(url, appId, appSecret, code);
		String openId = "";

		String resp = ReqToWeixin.httpGet(reqUrl);

		Gson gson = new Gson();

		HashMap<String, String> resultMap = gson.fromJson(resp, new TypeToken<HashMap<String, String>>() {
		}.getType());

		if (resultMap != null) {
			if (resultMap.containsKey("errcode")) {
				logger.error(resp);
			} else {
				openId = resultMap.get("openid");
			}
		}
		return openId;
	}

	/**
	 * test
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		Auth2UserInfo.getOpenId("01190ad1a5bdb7a9f681b571efb3d36e");
	}
}
